package ntu.edu.sg;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.view.SurfaceHolder;

// GameThread allows the game logic to run on a different thread than the GUI
// so that the graphics rendering and control wont be delayed by the logic calculations
public class GameThread extends Thread {

	// Handle to the surface manager object we interact with
	private SurfaceHolder _surfaceHolder;
	private Paint _paint; // to draw the ball and bats
	private Context _context;
	
	// Handle to the GameState
	private GameState _state;
	
	// a flag to indicate if game is in running mode
	private boolean mRun = false;

	// Constructor
	public GameThread(SurfaceHolder surfaceHolder, Context context, Handler handler)
	{
		_surfaceHolder = surfaceHolder;
		_paint = new Paint();
		_state = new GameState(context);
	}

	// Overriding default run method, 
	// which is called when a thread is instantiated
	@Override
	public void run() {
		
		// Entry point of the game loop
		// basically, checks for mRun flag
		// only execute actions if the flag is true
		while(mRun)
		{
			// Instantiate the surfaceholder canvas
			// and start editing mode
			Canvas canvas = _surfaceHolder.lockCanvas();
			// calls the instantiated GameState update method
			_state.update(_context);
			// calls the instantiated GameState draw method
			_state.draw(canvas,_paint);
			// ends surfaceholder editing mode
			_surfaceHolder.unlockCanvasAndPost(canvas);
		}
	}

	// getter for GameState, not used for now
	// but just leave it in case
	public GameState getGameState()
	{
		return _state;
	}
	
	// Method that is called to set the flag 
	// whether the game is in running mode,
	// or not
    public void setRunning(boolean b) {
        mRun = b;
    }

}